package com.ming.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Component
public class CorsInterceptor implements HandlerInterceptor {

    // 定义允许的前端地址白名单
    private static final List<String> ALLOWED_ORIGINS = Arrays.asList(
            "http://localhost:8080" // 将你的前端地址添加到这里
            // 如果有更多受信任的前端地址，可以继续添加
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String origin = request.getHeader("Origin");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            // 预检请求，可以设置更宽松的响应头
            handlePreflightRequest(response);
            return true;
        }

        if (isAllowedOrigin(origin)) {
            response.setHeader("Access-Control-Allow-Origin", origin);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
            response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        } else {
            // 如果不是允许的源，则不添加CORS头部信息，阻止请求
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);  // 返回403状态码
            return false;
        }

        return true;
    }

    private void handlePreflightRequest(HttpServletResponse response) {
        // 对于预检请求，允许所有来源，但实际请求时会检查来源是否在白名单中
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    }

    private boolean isAllowedOrigin(String origin) {
        // 检查请求的来源是否在允许的列表中
        return ALLOWED_ORIGINS.contains(origin);
    }
}